import fetch from '@system.fetch'
import app from '@system.app'
import tacticsConfig from '../json/tacticsConfig.json'
import storage from '@system.storage'
import device from '@system.device'
import pkg from '@system.package'
import CryptoJS from './aes'
import SECURE_UTIL from "../utils/secure_util.js"
import secretKeyConfig from '../json/tacticsSecret.json'
import newDefaultConfig from './newTacticsConfig.js'
let base_url =
  process.env.NODE_ENV == 'development'
    ? 'http://cldevapiold.senbowl.top/api'
    : 'https://clapi.senbowl.top/api'
/**
 * 用户上报数据 详细如下
 */
let report_data = {
  SECRET_KEY: '', // 应用身份KEY  必传
  HAPKEY: '', // HapKey 落地页传入
  INTENDED_USER: 0, // 是否意向用户 0否 1是 默认 0
  CHANNEL: '', // 渠道ID
  LINK_ID: '', // 链接ID
  SOURCE_PACKAGR: '', // 来源包名
  DEEP_LINK_ACCESS: 0, // deeplink 0否 1是 默认0
  REVIEW_STATUS: 0, //审核模式 0关 1开

  CLIENT_VERSION: '', // 客户端版本
  INSTALLED_PACKAGE_NAME: '', //  手机已安装包名
  TIMESTAMP: '', // 时间戳
  MOBIL_FACTORY: '', // 手机厂商 oppo vivo huawei xiaomi
  ANDROID_VERSION: '', // 安卓版本
  MOBIL_VERSION: '', // 手机型号
  QUICKAPP_VERSION: '', // 快应用版本
  ANDROID_ID: '', // 安卓id
  FIRST_VISITED_CITY: '',
  NUMBER_OF_VISITS: 0,
  MATERIAL_TYPE: '', //素材分类
  IDEAS_ID: '', //创意ID
  PLAN_ID: '', //计划ID
  UTM_SOURCE_ID: '', //媒体ID
  NUMBER_OF_VISITS_TODAY: '', //每天用户访问次数
  DATE_TIME: 0,
  LAST_VISITED_CITY: '', //最后一次访问城市
  INSTALL_APP: {},
  SOURCE_ID: '',
  OAID: '',
}
var global_data = {
  tacticsInfo: null, //策略信息
  routesInfo: [], //路由信息
  popupInfo: null, //弹窗信息
  initStatus: 0, //sdk初始化状态
  tacticsType: 4, //策略接口请求状态
  configInfo: null, //应用配置信息
  customPopupData: {}, //自定义弹窗信息
  backPopupData: {}, //返回退出自定义弹窗
  commonNativePopupData: {}, //自定义通用弹窗数据
  baiduPopupData: {}, //百度广告弹窗数据
  videoPopupData: {}, //视频广告弹窗数据
  middlePopupData: {}, //中插广告弹窗数据
  adPostionInfo: null,
  adConfigInfo: null,
  appPackageInfo: {},
  reviewStatus: 0, //是否审核用户
  ad_pool: null,
  ad_pool_custom: null,
  new_ad_pos: null, //阶梯广告位数据
  general_ad_pos: null, // ecpm广告位数据
  bqtAdConfigInfo: null, //白青藤广告数据
  qdConfig: {},
  middleVideoPopupData: {}, //中插视频广告弹窗数据
  middleBaiduPopupData: {}, //中插百度广告弹窗数据
  middleTempletePopupData: {}, //中插模板广告弹窗数据
  activity_name: '', //活动名称
  ts: 0, // 从投放页来的时间戳
  vistisTimes: 1,
  vistisTimesToday: 1,
  tacticsError: {},
  hotline: "", // 投诉热线
}
/**
 * 初始化SDK:
 * @param obj
 * obj.secretKey 应用身份key 必传
 * obj.android 安卓ID 必传
 * obj.deviceInfo 设备信息
 * obj.hapKey 落地页
 * obj.channelId 渠道ID
 * obj.linkId 链接ID
 * obj.deepLinkAccess deeplink 0否 1是 默认0
 * obj.intendedUser 是否为意向用户 0否 1是 默认0
 */
async function initSdk(obj) {
  return new Promise((resolve, reject) => {
    if (!obj.secretKey) {
      console.error('TACTICE_SDK->参数secretKey为必传')
      reject('SDK传入的参数advConfig为必传')
      return
    }
    if (!obj.android) {
      console.error('TACTICE_SDK->参数android为必传')
      reject('SDK传入的参数android为必传')
      return
    }
    global_data.initStatus = 1
    assignParame(obj).then(() => {
      LOG('TACTICS', 'TACTICE_SDK->初始化获取的城市以及访问次数', report_data)
      storage.get({ key: 'tacticsData' }).then((tacticsData) => {
        LOG('TACTICS', 'TACTICE_SDK->初始化获取的城市以及访问次数', tacticsData)
        if (tacticsData.data) {
          let data = JSON.parse(tacticsData.data)
          report_data.FIRST_VISITED_CITY = data.first_visited_city
            ? data.first_visited_city
            : ''
          report_data.LAST_VISITED_CITY = data.last_visited_city
            ? data.last_visited_city
            : ''
          report_data.NUMBER_OF_VISITS = data.number_of_visits
            ? Number(data.number_of_visits)
            : 0
          report_data.NUMBER_OF_VISITS_TODAY = data.number_of_visits_today
            ? Number(data.number_of_visits_today)
            : 0
          if (Number(data.date_time) != report_data.DATE_TIME) {
            report_data.NUMBER_OF_VISITS_TODAY = 0
          }
        }
        http('/users/sdk_init_v9', 'POST', report_data)
          .then((res) => {
            if (res.data.activity_name) {
              global_data.activity_name = res.data.activity_name
            }
            if (res.data.tacticsInfo) {
              global_data.tacticsInfo = SECURE_UTIL.decryptByAES(res.data.tacticsInfo, process.env.NODE_ENV == 'development' ? secretKeyConfig.dev : secretKeyConfig.pro)
              global_data.tacticsInfo.marketingTacticsName = res.data.marketingTacticsName
            } else {
              global_data.tacticsInfo = tacticsConfig.tacticsInfo
            }
            if (res.data.popupInfo) {
              global_data.popupInfo = res.data.popupInfo
            } else {
              global_data.popupInfo = tacticsConfig.popupInfo
            }
            if (res.data.ad_pool) {
              global_data.ad_pool = res.data.ad_pool
            } else {
              global_data.ad_pool = { status: 0, scene_list: '' }
            }
            if (res.data.ad_pool_custom) {
              global_data.ad_pool_custom = res.data.ad_pool_custom
            } else {
              global_data.ad_pool_custom = { status: 0, scene_list: '' }
            }

            // v2.3 add lf bg
            if (res.data.new_ad_pos) {
              global_data.new_ad_pos = res.data.new_ad_pos
            } else {
              global_data.new_ad_pos =
                newDefaultConfig.getNewDefaultAdPostionConfigByBrand(
                  report_data.MOBIL_FACTORY
                )
            }
            if (res.data.general_ad_pos) {
              global_data.general_ad_pos = res.data.general_ad_pos
            } else {
              global_data.general_ad_pos =
                newDefaultConfig.getNewsDefaultAdPostionConfigByBrand(
                  report_data.MOBIL_FACTORY
                )
            }

            if (res.data.ad_pos && res.data.ad_pos.baidu_ad) {
              global_data.bqtAdConfigInfo = res.data.ad_pos
            } else {
              global_data.bqtAdConfigInfo =
                newDefaultConfig.getBqtDefaultAdConfigByBrand(
                  report_data.MOBIL_FACTORY
                )
            }
            // v2.3 add lf end
            global_data.qdConfig = {
              ad_pos: res.data.ad_pos,
              ad_material: res.data.ad_material,
              ad_config: res.data.ad_config,
              page_config: res.data.page_config,
            }

            //sy v1.1.5 add bg
            if (res.data.configInfo) {
              global_data.configInfo = SECURE_UTIL.decryptByAES(res.data.configInfo, process.env.NODE_ENV == 'development' ? secretKeyConfig.dev : secretKeyConfig.pro)
              // global_data.configInfo = res.data.configInfo
            }
            //sy v1.1.5 add end
            if (res.data.routesInfo) {
              global_data.routesInfo = res.data.routesInfo
            } else {
              global_data.routesInfo = tacticsConfig.routesInfo
            }

            if (res.data.timeInfo) {
              global_data.timeInfo = res.data.timeInfo
            }
            if (res.data.first_visited_city && res.data.number_of_visits) {
              storage.set({
                key: 'tacticsData',
                value: {
                  first_visited_city: res.data.first_visited_city,
                  number_of_visits: res.data.number_of_visits,
                  number_of_visits_today: res.data.number_of_visits_today,
                  date_time: report_data.DATE_TIME,
                  last_visited_city: res.data.currently_visited_city,
                },
              })
            }

            if (res.data.hotline) {
              global_data.hotline = res.data.hotline
            } else {
              global_data.hotline = ""
            }

            global_data.vistisTimes = res.data.number_of_visits
            global_data.vistisTimesToday = res.data.number_of_visits_today
            global_data.reviewStatus = res.data.review_status

            global_data.initStatus = 2
            LOG('TACTICS', 'TACTICE_SDK->策略路由SDK初始化成功')
            global_data.tacticsType = 1
            resolve(global_data)
          })
          .catch((error) => {
            // 使用默认策略
            global_data.tacticsInfo = tacticsConfig.tacticsInfo
            global_data.routesInfo = tacticsConfig.routesInfo
            global_data.popupInfo = tacticsConfig.popupInfo

            global_data.new_ad_pos =
              newDefaultConfig.getNewDefaultAdPostionConfigByBrand(
                report_data.MOBIL_FACTORY
              )
            global_data.general_ad_pos =
              newDefaultConfig.getNewsDefaultAdPostionConfigByBrand(
                report_data.MOBIL_FACTORY
              )
            global_data.bqtAdConfigInfo =
              newDefaultConfig.getBqtDefaultAdConfigByBrand(
                report_data.MOBIL_FACTORY
              )
            global_data.ad_pool = { status: 0, scene_list: '' }
            //sy v1.1.5 add bg
            global_data.configInfo = tacticsConfig.configInfo
            //sy v1.1.5 add end

            global_data.timeInfo = tacticsConfig.timeInfo
            global_data.vistisTimes = 1
            global_data.vistisTimesToday = 1
            global_data.initStatus = 2
            console.error(
              'TACTICE_SDK->策略路由SDK初始化失败,初始化接口出错!已使用默认策略'
            )
            global_data.tacticsError = error
            global_data.tacticsType = 3
            global_data.hotline = ""
            resolve(global_data)
          })
      })
    })
  })
}

// 同步初始化传入的参数
function assignParame(obj) {
  LOG('TACTICS', '策略路由参数===>', obj)
  return new Promise(async (resolve) => {
    report_data.SECRET_KEY = obj.secretKey
    report_data.ANDROID_ID = obj.android
    report_data.OAID = obj.oaid
    report_data.CLIENT_VERSION = app.getInfo().versionName
    report_data.SOURCE_PACKAGR = app.getInfo().source.packageName
    report_data.TIMESTAMP = new Date().getTime()
    report_data.CHANNEL = obj.channelId ? obj.channelId : ''
    report_data.LINK_ID = obj.linkId ? obj.linkId : ''
    report_data.HAPKEY = obj.hapKey ? decodeURIComponent(obj.hapKey) : ''
    report_data.INTENDED_USER = obj.intendedUser ? obj.intendedUser : 0
    report_data.DEEP_LINK_ACCESS = obj.deepLinkAccess
    report_data.REVIEW_STATUS = obj.reviewStatus ? 1 : 0
    report_data.MATERIAL_TYPE = obj.materialType ? obj.materialType : ''
    report_data.IDEAS_ID = obj.ideasId ? obj.ideasId : ''
    report_data.PLAN_ID = obj.planId ? obj.planId : ''
    report_data.UTM_SOURCE_ID = obj.mediaId ? obj.mediaId : ''
    report_data.SOURCE_ID = obj.sourceId ? obj.sourceId : ''
    let time = new Date().getTime()
    let dayTime = (time - (time % 864e5)) / 864e5
    report_data.DATE_TIME = dayTime

    if (obj.deviceInfo) {
      report_data.QUICKAPP_VERSION = obj.deviceInfo.platformVersionCode
      report_data.ANDROID_VERSION = obj.deviceInfo.osVersionName
      report_data.MOBIL_VERSION = obj.deviceInfo.model
      let tembrand = obj.deviceInfo.brand && obj.deviceInfo.brand.toLowerCase()
      if (tembrand == 'huawei') {
        tembrand = 'huawei'
      } else if (tembrand == 'honor') {
        tembrand = 'honor'
      } else if (
        tembrand == 'redmi' ||
        tembrand == 'xiaomi' ||
        tembrand == '小米' ||
        tembrand == 'Redmi' ||
        tembrand == '小米红米'
      ) {
        tembrand = 'xiaomi'
      } else if (
        tembrand == 'oppo' ||
        tembrand == 'realme' ||
        tembrand == 'oneplus'
      ) {
        tembrand = 'oppo'
      } else if (tembrand == 'vivo') {
        tembrand = 'vivo'
      } else {
        tembrand = 'other'
      }
      report_data.MOBIL_FACTORY = tembrand
    } else {
      // 处理未接受到设备信息情况，主动请求再次读取一次
      device.getInfo().then((res) => {
        report_data.QUICKAPP_VERSION = res.data.platformVersionCode
        report_data.ANDROID_VERSION = res.data.osVersionName
        report_data.MOBIL_VERSION = res.data.model
        let tembrand = res.data.brand && res.data.brand.toLowerCase()
        if (tembrand == 'huawei') {
          tembrand = 'huawei'
        } else if (tembrand == 'honor') {
          tembrand = 'honor'
        } else if (
          tembrand == 'redmi' ||
          tembrand == 'xiaomi' ||
          tembrand == '小米' ||
          tembrand == 'Redmi' ||
          tembrand == '小米红米'
        ) {
          tembrand = 'xiaomi'
        } else if (
          tembrand == 'oppo' ||
          tembrand == 'realme' ||
          tembrand == 'oneplus'
        ) {
          tembrand = 'oppo'
        } else if (tembrand == 'vivo') {
          tembrand = 'vivo'
        } else {
          tembrand = 'other'
        }
        report_data.MOBIL_FACTORY = tembrand
      })
    }
    report_data.INSTALL_APP = await getRpkgTacticsList(report_data.MOBIL_FACTORY)
    resolve(1)
  })
}

function getRpkgTacticsList(brand) {
  let packageList = [
    "org.hapjs.debugger",
    "org.hapjs.mockup",
    "com.bytedance.ad.deliver",
    "com.baidu.fengchao.ui",
    "com.yiqixie.kem",
    "com.xiaomi.smartmijia",
    "com.iknow.client",
    "com.vivojsft.vmail",
    "com.huawei.works",
    "ch.com.vivo.hw.ctest",
    "com.baidu.hi",
    "cn.i4.mobile",
    "com.aikuai.ecloud",
    "com.systec.umeeting",
    "com.fvcorp.android.aijiasuclient",
    "com.lishun.flyfish",
    "com.qi.staticsproxy",
    "com.qi.earthnutproxy",
    "com.dongguo.feiyu",
    "com.wandou.network.wandoupod",
    "com.xiyan.xiniu",
    "com.mengdie.turtlenew",
    "com.chuangdian.ipjl2",
    "net.fly2cn.acc",
    "com.huawei.genexcloud.speedtest",
    "com.fobwifi.transocks",
    "cc.oasis.minor1",
    "com.cnqlx.booster",
    "com.max.maxaccelerator",
    "com.expressvpn.vpn",
    "top.a6b.shendunet",
  ], packageListBrand = []
  if (brand == 'huawei') {
    packageListBrand = [
      "com.huawei.fastapp.dev",
      "com.huawei.welink",
      "com.huawei.it.xinsheng"
    ]
  } else if (brand == 'xiaomi') {
    packageListBrand = [
      "com.mi.oa",
      "com.ss.android.lark",
      "com.ss.android.lark.kami"
    ]
  } else if (brand == 'oppo') {
    packageListBrand = [
      "com.teamtalk.im"
    ]
  } else if (brand == 'vivo') {
    packageListBrand = [
      "com.vivo.hybrid.sdkdemo",
      "com.vivo.hybrid.debugger",
      "com.sie.mp"
    ]
  } else if (brand == 'honor') {
    packageListBrand = [
      "com.huawei.fastapp.dev",
      "com.huawei.welink"
    ]
  }
  packageList = packageList.concat(packageListBrand)
  return new Promise((resolve) => {
    checkAbnormalPersonsFn(packageList, (res) => {
      LOG('TACTICS', 'checkAbnormalPersonsFn==>', res)
      resolve(aesEncrypt(JSON.stringify(res)))
    })
  })
}
// 检测应用
function checkAbnormalPersonsFn(packageList, callback) {
  let newObj = {}
  let currentCount = 0
  let curList = packageList.concat()
  checkPackage(newObj, currentCount, curList)
  function checkPackage(obj, index, list) {
    if (index >= list.length) {
      callback(obj)
    } else {
      pkg.hasInstalled({
        package: list[index],
        success: function (data) {
          if (data.result) {
            obj[`${list[index]}`] = 1
            index++
            checkPackage(obj, index, list)
          } else {
            obj[`${list[index]}`] = 0
            index++
            checkPackage(obj, index, list)
          }
        },
        fail: function (data, code) {
          obj[`${list[index]}`] = 0
          index++
          checkPackage(obj, index, list)
        },
      })
    }
  }
}
// 加密
function aesEncrypt(str) {
  try {
    // 算法是 AES-128-CBC
    var aes_key = CryptoJS.enc.Utf8.parse('00F35FCAA967B789') //十六位十六进制数作为密钥
    var aes_iv = CryptoJS.enc.Utf8.parse('A041FCA49EF0B983') //十六位十六进制数作为密钥偏移量

    var srcs = CryptoJS.enc.Utf8.parse(str)
    const encryptedData = CryptoJS.AES.encrypt(srcs, aes_key, {
      iv: aes_iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    })
    LOG('TACTICS', encryptedData.toString())
    return encryptedData.toString()
  } catch (err) {
    LOG('TACTICS', 'aesEncrypt', err)
    return str
  }
}
/**
 * 根据页面以及事件获取弹窗code
 * @param obj
 * obj.pageCode 页面标识
 * obj.actionCode 事件标识
 * obj.popupCode 弹窗标识
 * obj.pageOrigin 页面来源code
 */
function getPopupCodeByPageInfo(obj) {
  if (global_data.initStatus != 2) {
    console.error('TACTICE_SDK->SDK初始化未完成!')
    return ''
  }
  if (!obj.pageCode) {
    console.error('TACTICE_SDK->参数pageCode为必传!')
    return ''
  }
  if (!obj.actionCode) {
    console.error('TACTICE_SDK->参数actionCode为必传!')
    return ''
  }
  if (!obj.pageOrigin) {
    console.error('TACTICE_SDK->参数pageOrigin为必传!')
    return ''
  }
  // 事件为按钮以及弹窗关闭事件时，则需要另外的标识
  if (obj.actionCode == 'BUTTON_CLICK' || obj.actionCode == 'POPUP_CLOSE') {
    if (!obj.popupCode) {
      console.error(
        `TACTICE_SDK->事件为${obj.actionCode}时，popupCode不可以为空`
      )
      return ''
    }
  }
  if (global_data.tacticsInfo && global_data.tacticsInfo.pageTactics) {
    let tempArr = global_data.tacticsInfo.pageTactics.filter(
      (ele) =>
        ele.page_code == obj.pageCode && ele.page_origin == obj.pageOrigin
    )
    if (tempArr.length == 0) {
      if (obj.pageOrigin == 'ALL') {
        return false
      } else {
        return getPopupCodeByPageInfo({
          pageCode: obj.pageCode,
          actionCode: obj.actionCode,
          popupCode: obj.popupCode,
          pageOrigin: 'ALL',
        })
      }
    }
    let popupConfig = tempArr[0].popup_config
    if (!popupConfig.hasOwnProperty(`${obj.actionCode}`)) {
      if (obj.pageOrigin == 'ALL') {
        return false
      } else {
        return getPopupCodeByPageInfo({
          pageCode: obj.pageCode,
          actionCode: obj.actionCode,
          popupCode: obj.popupCode,
          pageOrigin: 'ALL',
        })
      }
    }
    var popupCode = ''
    switch (obj.actionCode) {
      case 'BUTTON_CLICK':
        // 按钮点击事件
        break
      case 'PAGE_BACK':
        // 页面返回
        popupCode =
          popupConfig.PAGE_BACK[0] && popupConfig.PAGE_BACK[0].popup_code
            ? popupConfig.PAGE_BACK[0].popup_code
            : ''
        break
      case 'PAGE_ENTRY':
        // 页面进入
        popupCode =
          popupConfig.PAGE_ENTRY[0] && popupConfig.PAGE_ENTRY[0].popup_code
            ? popupConfig.PAGE_ENTRY[0].popup_code
            : ''
        break
      case 'POPUP_CLOSE':
        // 弹窗关闭
        let codeInfo = popupConfig.POPUP_CLOSE.filter(
          (ele) => ele.popup_code == obj.popupCode
        )
        popupCode =
          codeInfo[0] && codeInfo[0].next_popup_code
            ? codeInfo[0].next_popup_code
            : ''
        break
      default:
        // 页面返回
        popupCode =
          popupConfig[`${obj.actionCode}`] &&
            popupConfig[`${obj.actionCode}`][0] &&
            popupConfig[`${obj.actionCode}`][0].popup_code
            ? popupConfig[`${obj.actionCode}`][0].popup_code
            : ''
        break
    }
    if (!popupCode && obj.pageOrigin == 'ALL') {
      return popupCode
    } else if (popupCode) {
      return popupCode
    } else {
      return getPopupCodeByPageInfo({
        pageCode: obj.pageCode,
        actionCode: obj.actionCode,
        popupCode: obj.popupCode,
        pageOrigin: 'ALL',
      })
    }
  } else {
    console.error('TACTICE_SDK->参数策略路由信息为空,请检查初始化或后台配置!')
    return ''
  }
}
/**
 * 根据公共弹窗code前缀获取完整弹窗code
 * @param obj.popupPrefix
 *
 */
function getCommonPopupCodeByPrefix(obj) {
  if (global_data.initStatus != 2) {
    console.error('TACTICE_SDK->SDK初始化未完成!')
    return ''
  }
  if (!obj.popupPrefix) {
    console.error('TACTICE_SDK->参数codePrefix为必传!')
    return ''
  }
  if (global_data.tacticsInfo && global_data.tacticsInfo.popups) {
    var resultCode = ''
    if (global_data.tacticsInfo.popups.indexOf(',') != -1) {
      let tempArr = global_data.tacticsInfo.popups
        .split(',')
        .filter((ele) => ele.split('_')[0] == obj.popupPrefix)
      if (tempArr.length > 0) {
        resultCode = tempArr[0]
      }
    } else {
      if (global_data.tacticsInfo.popups.split('_')[0] == obj.popupPrefix) {
        resultCode = global_data.tacticsInfo.popups
      }
    }
    LOG(
      'TACTICS',
      `TACTICE_SDK->前缀为${obj.popupPrefix}的弹窗完整code为${resultCode}`
    )
    return resultCode
  } else {
    console.error(
      ` ->公共弹窗获取失败!请检查是否配置${obj.popupPrefix}开头的公共弹窗？`
    )
    return ''
  }
}
/**
 * 根据页面code以及弹窗code前缀获取完整code
 * @param obj.pageCode
 * @param obj.popupPrefix
 */
function getPageCommonPopupCodeByPrefix(obj) {
  if (global_data.initStatus != 2) {
    console.error('TACTICE_SDK->SDK初始化未完成!')
    return ''
  }
  if (!obj.pageCode) {
    console.error('TACTICE_SDK->参数pageCode为必传!')
    return ''
  }
  if (!obj.popupPrefix) {
    console.error('TACTICE_SDK->参数popupPrefix为必传!')
    return ''
  }
  if (global_data.popupInfo && global_data.popupInfo[`${obj.pageCode}`]) {
    let popupList = global_data.popupInfo[`${obj.pageCode}`].split(',')
    let popCodeArr = popupList.filter(
      (item) => item.split('_')[0] == obj.popupPrefix
    )
    if (popCodeArr.length == 0) {
      return ''
    }
    LOG(
      'TACTICS',
      `TACTICE_SDK->策略路由匹配到的页面弹窗code为${popCodeArr[0]}_页面code为${obj.pageCode}`
    )
    return popCodeArr[0]
  } else {
    console.error(
      `TACTICE_SDK->页面弹窗获取失败!请检查页面${obj.pageCode}是否配置${obj.popupPrefix}开头的页面弹窗？`
    )
    return ''
  }
}
/**
 * 获取返回页面路由
 * @param curPageCode 当前页面code
 */
function getPageBackRouter(curPageCode) {
  if (!curPageCode) {
    console.error('TACTICE_SDK->参数curPageRouter为必传!')
    return ''
  }
  if (
    global_data.routesInfo &&
    global_data.routesInfo.routers &&
    global_data.routesInfo.routers.length > 1
  ) {
    var nextRouter = ''
    for (
      let index = 0;
      index < global_data.routesInfo.routers.length;
      index++
    ) {
      let item = global_data.routesInfo.routers[index]
      if (
        item.page_code == curPageCode &&
        index < global_data.routesInfo.routers.length - 1
      ) {
        nextRouter = global_data.routesInfo.routers[index + 1].router
      }
    }
    LOG('TACTICS', `TACTICE_SDK->获取返回页面路由结果${nextRouter}`)
    return nextRouter
  } else {
    console.error('TACTICE_SDK->暂无路由配置或者无效配置!')
    return ''
  }
}

/**
 * http 请求封装
 * @param  url   接口
 * @param  method  请求方法
 * @param  reqdata  请求参数
 */
async function http(url, method, reqdata) {
  return new Promise((resolve, reject) => {
    let headerSecure = {}
    if (url.indexOf('users/sdk_init_v9') > 0) {
      let randomNum = Math.floor(Math.random() * 10000 + 1)
      let curTime = global_data.ts && global_data.ts != '__TS__' ? global_data.ts : Date.now()
      let randomStr = `nonce=${randomNum}&android_id=${report_data.ANDROID_ID}&timestamp=${curTime}`
      headerSecure = {
        "X-Nonce": randomNum, //1-10000随机值
        "X-Api-Sign": SECURE_UTIL.encryptByAES(randomStr, process.env.NODE_ENV == 'development' ? secretKeyConfig.dev : secretKeyConfig.pro), // encryptByAES函数返回结果
        "X-Client-Utc": curTime + '', //当前时间戳，精确到秒级，当前sign有效期为100秒，超过100秒报签名错误
      }
    }
    fetch.fetch({
      url: base_url + url,
      method: method,
      data: reqdata,
      header: {
        'Content-Type': 'application/json',
        ...headerSecure
      },
      success: (data) => {
        LOG('TACTICS', 'http====>', data)
        try {
          const serverResponse = JSON.parse(data.data)
          if (serverResponse.code === 200) {
            resolve(serverResponse)
          } else {
            reject(serverResponse)
          }
        } catch (error) {
          reject('接口异常')
        }
      },
      fail: (data, code) => {
        LOG('TACTICS', `🐛tactics request fail, code = ${code} `, data)
        reject(data)
      },
    })
  })
}
/**
 * 获取应用配置 指定key的value值
 * @param {String} key config key值
 * @param {String} type 数据类型
 */
const getApplyConfig = (key, type = 's', val = '') => {
  const configInfo = getGlobalData('configInfo') && getGlobalData('configInfo')['config']
  type = type.toLowerCase()
  if (configInfo && configInfo[`${key}`]) {
    let data = ''
    switch (type) {
      case 'n':
        data = Number(configInfo[`${key}`].val)
        break
      case 'b':
        data = Boolean(Number(configInfo[`${key}`].val))
        break
      case 's':
      default:
        data = configInfo[`${key}`].val
        break
    }
    return data
  }
  return val ? val : type == 'n' ? 0 : type == 'b' ? false : ''
}
/**
 * 设置global_data 指定key的value值
 * @param {String} key global_data key值
 * @param {Object} val global_data value
 */
function setGlobalData(key, val) {
  if (!Object.keys(global_data).includes(key)) {
    console.error(
      `tactics_sdk setGlobalData key[${key}] is undefined ! Please check or add key[${key}]`
    )
    return
  }
  global_data[key] = val
}
/**
 * 获取global_data 指定key的value值
 * @param {String} key key值
 * @returns global_data key相对应的value
 */
function getGlobalData(key) {
  if (!Object.keys(global_data).includes(key)) {
    console.error(
      `tactics_sdk getGlobalData key[${key}]'s value is undefined ! Please check !`
    )
    return ''
  }
  return global_data[key]
}

/**
 * 获取 自定弹窗数据
 * @param {String} pop_code 自定义弹窗code
 */
function getCustomPopupData(pop_code) {
  return new Promise((resolve, reject) => {
    if (
      global_data.customPopupData &&
      global_data.customPopupData.hasOwnProperty(`${pop_code}`)
    ) {
      resolve(
        JSON.parse(JSON.stringify(global_data.customPopupData[`${pop_code}`]))
      )
      return
    }
    let packet = app.getInfo().source.packageName
    let secret_key = report_data.SECRET_KEY
    http(
      `/${pop_code.indexOf('Back') !== -1 ? 'back' : 'custom'}/json`,
      'GET',
      { secret_key, packet, pop_code }
    )
      .then((res) => {
        if (res.code == 200) {
          let list = JSON.parse(res.data)
          let obj = {}
          obj[`${pop_code}`] = list
          Object.assign(global_data.customPopupData, obj)
          resolve(JSON.parse(JSON.stringify(list)))
        } else {
          resolve([newDefaultConfig.CUSTOM_POP_DEFAULT_DATA])
        }
      })
      .catch((error) => {
        resolve([newDefaultConfig.CUSTOM_POP_DEFAULT_DATA])
      })
  })
}
/**
 * 获取 自定弹窗展示次数
 * @param {String} pop_code 自定义弹窗code
 */
async function sePopupShowTimes(pop_code) {
  let popRes = { data: '' }
  let popShowData = {}
  try {
    popRes = await storage.get({ key: 'popupShowInfo' })
  } catch (err) { }
  if (popRes.data) {
    popShowData = JSON.parse(popRes.data)
    if (popShowData.hasOwnProperty(`${pop_code}`)) {
      LOG('TACTICS', 'sePopupShowTimes======>2', popShowData, global_data.commonNativePopupData[`${pop_code}`], popShowData)
      popShowData[`${pop_code}`]++
      if (popShowData[`${pop_code}`] > global_data.commonNativePopupData[`${pop_code}`].length) {
        popShowData[`${pop_code}`] = 1
      }
      if (global_data.commonNativePopupData[`${pop_code}`][Number(popShowData[`${pop_code}`] - 1)].popKey === popShowData[`${pop_code + 'onShowPopKey'}`]) {
        // 当前弹窗组，上次展示弹窗与当前弹窗popKey相同，存入下一个popkey
        if (popShowData[`${pop_code}`] < global_data.commonNativePopupData[`${pop_code}`].length) {
          popShowData[`${pop_code + 'onShowPopKey'}`] = global_data.commonNativePopupData[`${pop_code}`][popShowData[`${pop_code}`]].popKey
        } else {
          // 当前弹窗组，上次展示弹窗与当前弹窗popKey相同并超过长度，存入下一轮popkey，重置展示次数
          popShowData[`${pop_code}`] = 1
          popShowData[`${pop_code + 'onShowPopKey'}`] = global_data.commonNativePopupData[`${pop_code}`][0].popKey
        }

      } else {
        // 当前弹窗组，上次展示弹窗与当前弹窗popKey不相同，存入当前popkey
        popShowData[`${pop_code + 'onShowPopKey'}`] = global_data.commonNativePopupData[`${pop_code}`][popShowData[`${pop_code}`] - 1].popKey

      }
    } else {
      let curObj = {}
      curObj[`${pop_code}`] = 1
      curObj[`${pop_code + 'onShowPopKey'}`] = global_data.commonNativePopupData[`${pop_code}`][0].popKey
      Object.assign(popShowData, curObj)

    }
  } else {
    let curObj = {}
    curObj[`${pop_code}`] = 1
    curObj[`${pop_code + 'onShowPopKey'}`] = global_data.commonNativePopupData[`${pop_code}`][0].popKey
    Object.assign(popShowData, curObj)
  }
  LOG('TACTICS', 'sePopupShowTimes======>3', popShowData)
  storage.set({ key: "popupShowInfo", value: popShowData })
}

/**
* 设置 自定弹窗展示次数
* @param {String} pop_code 自定义弹窗code
*/
function gePopupShowTimes(pop_code) {
  return new Promise((resolve) => {
    storage.get({
      key: "popupShowInfo",
      success(res) {
        if (res) {
          let showInfo = JSON.parse(res)
          if (typeof showInfo == 'object' && showInfo.hasOwnProperty(`${pop_code}`) && global_data.commonNativePopupData[`${pop_code}`]) {
            // 当前弹窗组，展示次数等于弹窗组长度时重置展示次数
            if (Number(showInfo[`${pop_code}`]) >= global_data.commonNativePopupData[`${pop_code}`].length) {
              showInfo[`${pop_code}`] = 0
            }
            // 当前弹窗组，上次展示弹窗与当前弹窗popKey相同，返回弹窗组下一个弹窗
            if (global_data.commonNativePopupData[`${pop_code}`][Number(showInfo[`${pop_code}`])].popKey === showInfo[`${pop_code + 'onShowPopKey'}`]) {
              showInfo[`${pop_code}`]++
            }
            return resolve(Number(showInfo[`${pop_code}`]))
          }
        }
        resolve(0)
      },
      fail(data, code) {
        resolve(0)
      }
    })
  })
}


/**
 * 获取 返回退出自定弹窗数据
 * @param {String} pop_code 自定义弹窗code
 */
function geBackPopupData(pop_code) {
  return new Promise((resolve, reject) => {
    if (
      global_data.backPopupData &&
      global_data.backPopupData.hasOwnProperty(`${pop_code}`)
    ) {
      resolve(
        JSON.parse(JSON.stringify(global_data.backPopupData[`${pop_code}`]))
      )
      return
    }
    let packet = app.getInfo().source.packageName
    let secret_key = report_data.SECRET_KEY
    http('/back/json', 'GET', { secret_key, packet, pop_code })
      .then((res) => {
        if (res.code == 200) {
          let list = JSON.parse(res.data)
          let obj = {}
          obj[`${pop_code}`] = list
          Object.assign(global_data.backPopupData, obj)
          resolve(JSON.parse(JSON.stringify(list)))
        } else {
          resolve([newDefaultConfig.CUSTOM_BACK_POP_DEFAULT_DATA])
        }
      })
      .catch((error) => {
        resolve([newDefaultConfig.CUSTOM_BACK_POP_DEFAULT_DATA])
      })
  })
}

function getCommonNativePopupData(pop_code) {
  return new Promise((resolve, reject) => {
    if (
      global_data.commonNativePopupData &&
      global_data.commonNativePopupData.hasOwnProperty(`${pop_code}`)
    ) {
      resolve(
        JSON.parse(
          JSON.stringify(global_data.commonNativePopupData[`${pop_code}`])
        )
      )
      return
    }
    let packet = app.getInfo().source.packageName
    let secret_key = report_data.SECRET_KEY
    http('/common/json', 'GET', { secret_key, packet, group_code: pop_code })
      .then((res) => {
        if (res.code == 200) {
          let list = JSON.parse(res.data)
          let obj = {}
          obj[`${pop_code}`] = list
          Object.assign(global_data.commonNativePopupData, obj)
          resolve(JSON.parse(JSON.stringify(list)))
        } else {
          resolve(newDefaultConfig.COMMON_NATIVE_POP_DEFAULT_DATA)
        }
      })
      .catch((error) => {
        resolve(newDefaultConfig.COMMON_NATIVE_POP_DEFAULT_DATA)
      })
  })
}
function getEncouragePopupData(pop_code) {
  return new Promise((resolve, reject) => {
    if (
      global_data.videoPopupData &&
      global_data.videoPopupData.hasOwnProperty(`${pop_code}`)
    ) {
      resolve(
        JSON.parse(JSON.stringify(global_data.videoPopupData[`${pop_code}`]))
      )
      return
    }
    let packet = app.getInfo().source.packageName
    let secret_key = report_data.SECRET_KEY
    http('/encourage/json', 'GET', { secret_key, packet, group_code: pop_code })
      .then((res) => {
        if (res.code == 200) {
          let list = JSON.parse(res.data)
          let obj = {}
          obj[`${pop_code}`] = list
          Object.assign(global_data.videoPopupData, obj)
          resolve(JSON.parse(JSON.stringify(list)))
        } else {
          resolve(newDefaultConfig.COMMON_VIDEO_POP_DEFAULT_DATA)
        }
      })
      .catch((error) => {
        resolve(newDefaultConfig.COMMON_VIDEO_POP_DEFAULT_DATA)
      })
  })
}
function getBaiduPopupData(pop_code) {
  return new Promise((resolve, reject) => {
    if (
      global_data.baiduPopupData &&
      global_data.baiduPopupData.hasOwnProperty(`${pop_code}`)
    ) {
      resolve(
        JSON.parse(JSON.stringify(global_data.baiduPopupData[`${pop_code}`]))
      )
      return
    }
    let packet = app.getInfo().source.packageName
    let secret_key = report_data.SECRET_KEY
    http('/baidu/json', 'GET', { secret_key, packet, group_code: pop_code })
      .then((res) => {
        if (res.code == 200) {
          let list = JSON.parse(res.data)
          let obj = {}
          obj[`${pop_code}`] = list
          Object.assign(global_data.baiduPopupData, obj)
          resolve(JSON.parse(JSON.stringify(list)))
        } else {
          resolve(newDefaultConfig.COMMON_BAIDU_POP_DEFAULT_DATA)
        }
      })
      .catch((error) => {
        resolve(newDefaultConfig.COMMON_BAIDU_POP_DEFAULT_DATA)
      })
  })
}

function getMiddlePopupData(pop_code) {
  return new Promise((resolve, reject) => {
    if (
      global_data.middlePopupData &&
      global_data.middlePopupData.hasOwnProperty(`${pop_code}`)
    ) {
      resolve(
        JSON.parse(JSON.stringify(global_data.middlePopupData[`${pop_code}`]))
      )
      return
    }
    let packet = app.getInfo().source.packageName
    let secret_key = report_data.SECRET_KEY
    http('/middle/native', 'GET', { secret_key, packet, group_code: pop_code })
      .then((res) => {
        if (res.code == 200) {
          let list = JSON.parse(res.data)
          let obj = {}
          obj[`${pop_code}`] = list
          Object.assign(global_data.middlePopupData, obj)
          resolve(JSON.parse(JSON.stringify(list)))
        } else {
          resolve(newDefaultConfig.COMMON_MIDDLE_POP_DEFAULT_DATA)
        }
      })
      .catch((error) => {
        resolve(newDefaultConfig.COMMON_MIDDLE_POP_DEFAULT_DATA)
      })
  })
}

function getMiddleVideoPopupData(pop_code) {
  return new Promise((resolve, reject) => {
    if (
      global_data.middleVideoPopupData &&
      global_data.middleVideoPopupData.hasOwnProperty(`${pop_code}`)
    ) {
      resolve(
        JSON.parse(
          JSON.stringify(global_data.middleVideoPopupData[`${pop_code}`])
        )
      )
      return
    }
    let packet = app.getInfo().source.packageName
    let secret_key = report_data.SECRET_KEY
    http('/middle/video', 'GET', { secret_key, packet, group_code: pop_code })
      .then((res) => {
        if (res.code == 200) {
          let list = JSON.parse(res.data)
          let obj = {}
          obj[`${pop_code}`] = list
          Object.assign(global_data.middleVideoPopupData, obj)
          resolve(JSON.parse(JSON.stringify(list)))
        } else {
          resolve(newDefaultConfig.COMMON_MIDDLE_POP_DEFAULT_DATA)
        }
      })
      .catch((error) => {
        resolve(newDefaultConfig.COMMON_MIDDLE_POP_DEFAULT_DATA)
      })
  })
}
function getMiddleTempletePopupData(pop_code) {
  return new Promise((resolve, reject) => {
    if (
      global_data.middleTempletePopupData &&
      global_data.middleTempletePopupData.hasOwnProperty(`${pop_code}`)
    ) {
      resolve(
        JSON.parse(
          JSON.stringify(global_data.middleTempletePopupData[`${pop_code}`])
        )
      )
      return
    }
    let packet = app.getInfo().source.packageName
    let secret_key = report_data.SECRET_KEY
    http('/middle/templete', 'GET', {
      secret_key,
      packet,
      group_code: pop_code,
    })
      .then((res) => {
        if (res.code == 200) {
          let list = JSON.parse(res.data)
          let obj = {}
          obj[`${pop_code}`] = list
          Object.assign(global_data.middleTempletePopupData, obj)
          resolve(JSON.parse(JSON.stringify(list)))
        } else {
          resolve(newDefaultConfig.COMMON_TEMPLETE_POP_DEFAULT_DATA)
        }
      })
      .catch((error) => {
        resolve(newDefaultConfig.COMMON_TEMPLETE_POP_DEFAULT_DATA)
      })
  })
}
function getMiddleBaiduPopupData(pop_code) {
  return new Promise((resolve, reject) => {
    if (
      global_data.middleBaiduPopupData &&
      global_data.middleBaiduPopupData.hasOwnProperty(`${pop_code}`)
    ) {
      resolve(
        JSON.parse(
          JSON.stringify(global_data.middleBaiduPopupData[`${pop_code}`])
        )
      )
      return
    }
    let packet = app.getInfo().source.packageName
    let secret_key = report_data.SECRET_KEY
    http('/middle/baidu', 'GET', { secret_key, packet, group_code: pop_code })
      .then((res) => {
        if (res.code == 200) {
          let list = JSON.parse(res.data)
          let obj = {}
          obj[`${pop_code}`] = list
          Object.assign(global_data.middleBaiduPopupData, obj)
          resolve(JSON.parse(JSON.stringify(list)))
        } else {
          resolve(newDefaultConfig.COMMON_MIDDLE_POP_DEFAULT_DATA)
        }
      })
      .catch((error) => {
        resolve(newDefaultConfig.COMMON_MIDDLE_POP_DEFAULT_DATA)
      })
  })
}
//  获取行为下广告逻辑弹窗code
/**
 *
 * @param {string} action       当前行为
 * @param {string} adStatus     当前请求状态
 * @param {string} pageCode     当前页面
 * @param {string} pageOrigin   页面来源
 * @returns
 */
function getActionPopupCode(action, adStatus, pageCode, pageOrigin) {
  LOG('策略sdk mxt:getActionPopupCode ', action, adStatus, pageCode, pageOrigin)
  return new Promise((resolve, reject) => {
    if (global_data.tacticsInfo && global_data.tacticsInfo.pageTactics) {
      let actionInfo = global_data.tacticsInfo.pageTactics.filter((item) => {
        if (item.page_code == pageCode && item.page_origin == pageOrigin) {
          return item
        }
      })
      let allActionInfo = global_data.tacticsInfo.pageTactics.filter((item) => {
        if (item.page_code == pageCode && item.page_origin == 'ALL') {
          return item
        }
      })
      LOG('策略sdk mxt :actionInfo', actionInfo, allActionInfo)
      if (actionInfo.length > 0 || allActionInfo.length > 0) {
        if (
          actionInfo.length &&
          actionInfo[0].popup_config[action] &&
          actionInfo[0].popup_config[action].length > 0 &&
          actionInfo[0].popup_config[action][0]['action'] &&
          actionInfo[0].popup_config[action][0]['action'][adStatus]
        ) {
          resolve(actionInfo[0].popup_config[action][0]['action'][adStatus])
        } else if (
          allActionInfo.length &&
          allActionInfo[0].popup_config[action] &&
          allActionInfo[0].popup_config[action].length > 0 &&
          allActionInfo[0].popup_config[action][0]['action'] &&
          allActionInfo[0].popup_config[action][0]['action'][adStatus]
        ) {
          resolve(allActionInfo[0].popup_config[action][0]['action'][adStatus])
        } else {
          reject('withoutCode')
        }
      } else {
        reject('withoutCode')
      }
    } else {
      reject('withoutCode')
    }
  })
}
/**
 * 检查当前code 是否为替换code
 *
 * @returns  原始code
 */
function getOriginalPopCode(pageCode, pageOrigin, actionCode, popupCode) {
  LOG(
    '策略sdk mxt:getActionPopupCode ',
    pageCode,
    pageOrigin,
    actionCode,
    popupCode
  )
  return new Promise((resolve, reject) => {
    if (global_data.tacticsInfo && global_data.tacticsInfo.pageTactics) {
      let actionInfo = global_data.tacticsInfo.pageTactics.filter((item) => {
        if (item.page_code == pageCode && item.page_origin == pageOrigin) {
          return item
        }
      })
      LOG('策略sdk mxt :actionInfo', actionInfo)
      if (
        actionInfo.length > 0 &&
        actionInfo[0]['popup_config'][actionCode] &&
        actionInfo[0]['popup_config'][actionCode][0] &&
        actionInfo[0]['popup_config'][actionCode][0].action
      ) {
        LOG(
          '== 策略sdk mxt :click_interval',
          actionInfo[0]['popup_config'][actionCode][0].action.click_interval
        )
        LOG(
          '== 策略sdk mxt :request_fail',
          actionInfo[0]['popup_config'][actionCode][0].action.request_fail
        )
        if (
          actionInfo[0]['popup_config'][actionCode][0].action.click_interval ==
          popupCode ||
          actionInfo[0]['popup_config'][actionCode][0].action.request_fail ==
          popupCode
        ) {
          LOG(
            '== 策略sdk mxt :popup_code',
            actionInfo[0]['popup_config'][actionCode][0].popup_code
          )
          if (actionCode == 'POPUP_CLOSE') {
            resolve(
              actionInfo[0]['popup_config'][actionCode][0].next_popup_code
            )
          } else {
            resolve(actionInfo[0]['popup_config'][actionCode][0].popup_code)
          }
        }
      }
    }
    resolve(popupCode)
  })
}

// 获取广告配置信息 从策略v3接口获取的数据中获取
function getNewAdPostionInfo() {
  let _curConfig = null
  if (global_data.general_ad_pos) {
    _curConfig = global_data.general_ad_pos
  }
  return _curConfig
}
// 获取白青藤广告配置信息 从策略v3接口获取的数据中获取
function getBqtAdConfigInfo() {
  let _curConfig = null
  if (global_data.bqtAdConfigInfo) {
    _curConfig = global_data.bqtAdConfigInfo
  } else {
    let brand = report_data.MOBIL_FACTORY
    _curConfig = newDefaultConfig.getBqtDefaultAdConfigByBrand(brand)
  }
  return _curConfig
}

function getQdConfig(code) {
  if (code) {
    return global_data.qdConfig[code] || {}
  } else {
    return global_data.qdConfig
  }
}

const TACTICS_SDK = {
  initSdk: initSdk, //sdk初始化
  getPopupCodeByPageInfo, //获取弹窗code
  getPageBackRouter, //获取返回路由
  getCommonPopupCodeByPrefix, //根据公共弹窗code前缀获取完整code
  getPageCommonPopupCodeByPrefix, //根据页面code以及弹窗code前缀获取完整code
  setGlobalData, //设置global_data 指定key的value值
  getGlobalData, //获取global_data 指定key的value值
  getCustomPopupData, //获取 自定弹窗数据
  geBackPopupData, //获取返回弹窗数据
  gePopupShowTimes, //获取弹窗展示次数
  sePopupShowTimes, //弹窗展示次数修改
  // v2.3add  lf bg
  getNewAdPostionInfo, //获取新的广告位id 信息
  getBqtAdConfigInfo, //获取白青藤广告位配置
  getCommonNativePopupData: getCommonNativePopupData, //获取自定义通用弹窗数据
  getEncouragePopupData: getEncouragePopupData, //获取视频广告弹窗数据
  getBaiduPopupData: getBaiduPopupData, //获取视频广告弹窗数据
  getActionPopupCode, // 获取行为下广告逻辑弹窗code
  getOriginalPopCode, // 根据当前传入的code 获取原始code
  getQdConfig: getQdConfig,
  getMiddlePopupData: getMiddlePopupData, //获取中插原生广告配置
  getMiddleVideoPopupData, //获取中插视频广告配置
  getMiddleBaiduPopupData, //获取中插百度广告配置
  getMiddleTempletePopupData, //获取中插模板广告配置
  getApplyConfig, // 获取应用配置信息
  checkAbnormalPersonsFn,
}
const tactic_global = global.__proto__ || global
tactic_global.TACTICS_SDK = TACTICS_SDK
export default TACTICS_SDK
